﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using TimeToGo.Infrastructure;

namespace TimeToGo.Presentation.ViewModels
{
    internal class EditTimeViewModel : ViewModelBase
    {
        public SimpleDelegateCommand<object> OkCommand { get; set; }
        public SimpleDelegateCommand<object> CancelCommand { get; set; }

        private IEditTimeView _view;
        private TimeInfo _timeInfo;
        private IList<TimeInfo> _times;

        public EditTimeViewModel(TimeInfo timeInfo, IList<TimeInfo> times, IEditTimeView view)
        {
            _timeInfo = timeInfo;
            _times = times;
            _view = view;

            if (_timeInfo != null)
            {
                _name = _timeInfo.Name;
                _time = _timeInfo.Time.ToString();
            }
            else
            {
                _time = DateTime.Now.ToString();
            }
             
            OkCommand = new SimpleDelegateCommand<object>(Ok);
            CancelCommand = new SimpleDelegateCommand<object>(Cancel);
        }

        private void Ok(object parameter)
        {
            if (string.IsNullOrEmpty(Name))
            {
                _view.DisplayErrorMessage("You must enter a name");
                return;
            }

            if (_times.FirstOrDefault(t => t.Name == Name) != null)
            {
                _view.DisplayErrorMessage("Name already in use, please choose another.");
                return;
            }

            DateTime time;
            if (!DateTime.TryParse(_time, out time))
            {    
                _view.DisplayErrorMessage("Invalid time");
                return;
            }

            if (_timeInfo == null)
                _timeInfo = new TimeInfo();

            _timeInfo.Name = Name;
            _timeInfo.Time = time;
            _view.Close();
        }

        private void Cancel(object parameter)
        {
            // this is a hack...!
            _timeInfo.Name = null;
            _view.Close();
        }

        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                if (_name != value)
                {
                    _name = value;
                    OnPropertyChanged("Name");
                }
            }
        }

        private string _time;
        public string Time
        {
            get { return _time; }
            set
            {
                if (_time != value)
                {
                    _time = value;
                    OnPropertyChanged("Time");
                }
            }
        }
    }
}
